#include "client.h"

int loginFunc(int sockfd){
    int try_times=3;
    int state;
    train_t train_name;
    train_t train_password;

    //登录操作
    bzero(&train_name,sizeof(train_name));
    bzero(&train_password,sizeof(train_password));

    printf("请输入用户名:");
    fgets(train_name.data,sizeof(train_name.data),stdin);
    train_name.data[strlen(train_name.data)-1]='\0';
    train_name.length=strlen(train_name.data);
    printf("%s\n",train_name.data);

    printf("请输入用户密码：");
    fgets(train_password.data,sizeof(train_password.data),stdin);
    train_password.data[strlen(train_password.data)-1]='\0';
    train_password.length=strlen(train_password.data);

    //向服务端发送
    send(sockfd,&train_name,sizeof(train_name.length)+train_name.length,MSG_NOSIGNAL);
    send(sockfd,&train_password,sizeof(train_password.length)+train_password.length,MSG_NOSIGNAL);

    while(1){
        recv(sockfd,&state,sizeof(int),0);
        if(state==0){
            return 0;
        }
        if(state==1){
            try_times--;
            if(try_times==0){
                return 1;
            }
            printf("密码错误\n");
            bzero(&train_password,sizeof(train_password));
            printf("请输入密码：\n");
            fgets(train_password.data,sizeof(train_password.data),stdin);
            train_password.data[strlen(train_password.data)-1]='\0';
            train_password.length=strlen(train_password.data);
            send(sockfd,&train_name,sizeof(train_name.length)+train_name.length,MSG_NOSIGNAL);
            send(sockfd,&train_password,sizeof(train_password.length)+train_password.length,MSG_NOSIGNAL);
            
        }
        if(state==2){
            
            printf("不存在\n");
            return 2;
        }
    }
    return 3;
}
